package com.whmskj.xjlhsc.qianYiData.service.impl;

import com.whmskj.xjlhsc.qianYiData.mapper.The21stMapper;
import com.whmskj.xjlhsc.qianYiData.service.The21stService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.YearMonth;

@Service
public class The21stServiceImpl implements The21stService {

    @Resource
    private The21stMapper mapper;

    @Override
    public int syncByBaseDate(LocalDate baseDate) {
        if (baseDate == null) baseDate = LocalDate.now();
        // 计算“21~20”窗口与归属月份
        Window w = calcWindow(baseDate);
        int updated = mapper.updateFromDailyCopy(w.monthFirst, w.startDay, w.endDay);
        int inserted = mapper.insertMissingFromDailyCopy(w.monthFirst, w.startDay, w.endDay);
        return updated + inserted;
    }

    /**
     * 以 baseDate 计算结算窗口与归属月份：
     * - 若 baseDate.day <= 20：窗口=上月21~本月20，归属月份=本月
     * - 若 baseDate.day > 20：窗口=本月21~下月20，归属月份=下月
     */
    private Window calcWindow(LocalDate baseDate) {
        int day = baseDate.getDayOfMonth();
        if (day <= 20) {
            LocalDate monthFirst = baseDate.withDayOfMonth(1); // 本月1号
            LocalDate start = baseDate.minusMonths(1).withDayOfMonth(21);
            LocalDate end = baseDate.withDayOfMonth(20);
            return new Window(monthFirst, start, end);
        } else {
            YearMonth next = YearMonth.from(baseDate).plusMonths(1);
            LocalDate monthFirst = next.atDay(1); // 下月1号
            LocalDate start = baseDate.withDayOfMonth(21);
            LocalDate end = next.atDay(20);
            return new Window(monthFirst, start, end);
        }
    }

    private static class Window {
        final LocalDate monthFirst; // 归属月份(1号)
        final LocalDate startDay;   // 窗口开始(21)
        final LocalDate endDay;     // 窗口结束(20)
        Window(LocalDate monthFirst, LocalDate startDay, LocalDate endDay) {
            this.monthFirst = monthFirst;
            this.startDay = startDay;
            this.endDay = endDay;
        }
    }
}

